#!/usr/bin/env python3
import socket
import struct
import os
import time
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Send an archive file and get an archive and log files")
    parser.add_argument("--direction", required=True, help="Path to the input file input|output")
    parser.add_argument("--cachedir", required=False, help="Path to the output file")
    parser.add_argument("--archive", required=False, help="Path to the output file")
    parser.add_argument("--ip", required=True, help="IP address to append")
    parser.add_argument("--port", required=True, help="IP address to append")
    args = parser.parse_args()
    print(args)
    retcode = 0
    try : 
        if args.direction == "output":
            
            if args.archive == None:
                parser.error("--direction output needs --archive ")
        elif args.direction == "input":
            if args.cachedir == None:
                parser.error("--direction input needs --cachedir ")
        else :
            parser.error("--direction can be only input or output")
    except:
        pass

    host = args.ip
    port = int(args.port)
    dir = args.direction
    filename = args.archive

    RECEIVED_RESPONSE_FILES = [ "archive.tar", "logging_conf_lib_error_log.xf","log2" ]  # File to save server's response


    try :
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
            client_socket.connect((host, port))

            if dir == "output":

                # Ensure file exists before proceeding
                if not os.path.exists(filename):
                        print(f"Error: {filename} not found!")
                        exit()
                file_size = os.path.getsize(filename)

                # Send command (8 bytes )
                client_socket.sendall(struct.pack("!Q", 1))

                # Send file size (8 bytes for large files)
                client_socket.sendall(struct.pack("!Q", file_size))

                # Send file data in chunks
                with open(filename, "rb") as file:
                    while chunk := file.read(1024):
                        client_socket.sendall(chunk)

                print(f"File {filename} sent successfully ({file_size} bytes).")
            elif dir == "input":
                 # Send command (8 bytes )
                client_socket.sendall(struct.pack("!Q", 2))
                
                for RECEIVED_RESPONSE_FILE in RECEIVED_RESPONSE_FILES:

                    # Receive response file size
                    file_size_data = client_socket.recv(8)
                    file_size = struct.unpack("!Q", file_size_data)[0]
                    print(f"Response file size: {file_size} bytes")

                

                    # Receive response file data
                    with open(RECEIVED_RESPONSE_FILE, "wb") as file:
                        received = 0
                        while received < file_size:
                            chunk = client_socket.recv(1024)
                            if not chunk:
                                break
                            file.write(chunk)
                            received += len(chunk)

                    print(f"Response file {RECEIVED_RESPONSE_FILE} received successfully!")
    except Exception as e:
        print(e)
        retcode = -1
    print("Connection closed.")
    return retcode

if __name__ == "__main__":
    retcode = main()
    sys.exit(retcode)    
    
        

    
